import React from 'react';
import PropTypes from 'prop-types';
import { Table, Tag, Balloon, Button } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { Title } from '@alife/devops-ui';
import './index.scss';
import exceed from 'utils/apimap';
import ListEmpty from 'atComponents/ListEmpty';
import utils from 'utils';
import isEqual from 'lodash.isequal';
import IssueIdialog from './issueDetailDialog';
import UsersAvatar from '@alife/teamix-at-users-avatar';
import dayjs from 'dayjs';
import { ENUM } from 'utils/constants';
import PathEllipsis from 'components/pathEllipsis';
import intl from '../../locale';

const { Tooltip } = Balloon;

const levelMap = {
  Blocker: 'red',
  Major: 'blue',
  Critical: 'orange',
};

const stateMap = ENUM.issueStausMap;

const defaultPerPage = 12;

export default class IssuesTable extends React.Component {
  static propTypes = {
    headerTitle: PropTypes.string,
    // 表格状态分类
    issue_status: PropTypes.string,
  };

  static defaultProps = {
    headerTitle: '',
    issue_status: '',
  };

  constructor(props) {
    super(props);
    this.state = {
      expandRow: true,
      dataSource: null,
      page: 1,
      openRowKeys: this.props.issue_status === 'unresolved' ? [0] : [],
      isLoading: true,
      isModalOpen: false,
      issue: null,
    };
  }

  componentDidMount() {
    const { buildResult, filterParams } = this.props;
    this.listBuildIssues(buildResult, filterParams);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { buildResult: nextBuildResult, filterParams: nextFilterParams } = nextProps;
    const { buildResult, filterParams } = this.props;
    if (
      nextBuildResult &&
      buildResult &&
      (nextBuildResult.id !== buildResult.id || !isEqual(filterParams, nextFilterParams))
    ) {
      this.listBuildIssues(nextBuildResult, nextFilterParams);
    }
  }

  listBuildIssues = (buildResult, filterParams, page = 1) => {
    const { pathResource } = window.FORCE;
    if (buildResult) {
      this.setState({
        isLoading: true,
      });

      const datas = {};
      if (filterParams.issue_level_list && filterParams.issue_level_list.length > 0) {
        datas.level = filterParams.issue_level_list.join(',');
      }
      if (filterParams.users && filterParams.users.length > 0) {
        datas.author_id = filterParams.users
          .map((item) => {
            return item._userId;
          })
          .join(',');
      }
      if (filterParams.start_time) {
        datas.start_time = filterParams.start_time;
      }
      if (filterParams.end_time) {
        datas.end_time = filterParams.end_time;
      }
      exceed
        .forceFetch({
          api: 'projects.builds.list.issues',
          params: {
            projectId: pathResource.id,
            buildResultId: buildResult.id,
          },

          data: {
            page,
            per_page: defaultPerPage,
            issue_status:
              this.props.issue_status === 'unresolved' ? 'unresolved,new' : this.props.issue_status,
            ...datas,
          },
        })
        .then((data) => {
          this.setState({
            dataSource: data,
            page,
            isLoading: false,
          });
        })
        .catch((err) => {
          console.error(err);
          this.setState({
            isLoading: false,
          });
        });
    }
  };

  toggleRow = () => {
    const { expandRow } = this.state;
    this.setState({
      expandRow: !expandRow,
    });
  };

  onPageNoChange = (page) => {
    const { buildResult, filterParams } = this.props;
    this.listBuildIssues(buildResult, filterParams, page);
  };

  onRowOpen = (openRowKeys) => {
    this.setState({
      openRowKeys,
    });
  };

  renderLevel = (value) => {
    return (
      <div style={{ marginLeft: '-4px' }}>
        <Tag color={levelMap[value] || undefined}>{value}</Tag>
      </div>
    );
  };

  renderOwner = (value, index, record) => {
    return (
      <div style={{ marginLeft: 5, display: 'flex', alignItems: 'center' }}>
        <UsersAvatar
          dataSource={[
            {
              id: '',
              name: value,
              avatarUrl: record.avatar || '',
            },
          ]}
          size="xs"
          borderColor={'#f7f7f7'}
        />

        <Title trigger={<span style={{ marginLeft: 8 }}>{value}</span>} align="t">
          <span>{value}</span>
        </Title>
      </div>
    );
  };

  handleRowClick = (record) => {
    this.setState({
      isModalOpen: true,
      issue: record,
    });
  };

  onClose = () => {
    this.setState({
      issue: null,
      isModalOpen: false,
    });
  };

  renderTitle = (value) => {
    const content = (
      <Tooltip
        trigger={
          <div style={{ marginLeft: '24px' }} className="table-cell-one-line">
            {value}
          </div>
        }
        align="t"
      >
        {value}
      </Tooltip>
    );

    return <div>{content}</div>;
  };

  renderFile = (value) => {
    return (
      <div className="pippoint-file-name-content">
        <PathEllipsis path={value} isLastItemMoreImportant={false} />
      </div>
    );
  };

  renderStatus = (value) => {
    const status = value.toLowerCase();
    return (
      <div style={{ marginLeft: '-4px' }}>
        <Tag color={stateMap[status].color}>{stateMap[status].text}</Tag>
      </div>
    );
  };

  isHasFilter() {
    const { filterParams } = this.props;
    if (!filterParams) {
      return false;
    }
    if (
      filterParams.start_time ||
      filterParams.end_time ||
      (filterParams.users && filterParams.users.length > 0) ||
      (filterParams.issue_level_list && filterParams.issue_level_list.length > 0)
    ) {
      return true;
    } else {
      return false;
    }
  }

  renderEmptyList() {
    const { issue_status, buildResult, restartScan, isStarting } = this.props;
    if (this.isHasFilter()) {
      return (
        <ListEmpty
          content={''}
          desc={intl.get({
            id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.NoSearchResults',
            defaultMessage: '搜索无结果',
          })}
          className="table-result"
          size="small"
          imgType="search"
        />
      );
    } else {
      // FAIL和WARNNING状态，没有返回issues，判断检测时间，超过30天，显示PRD里文案「xxx仅保持30天据」
      const { state, gmt_create } = buildResult;
      if (
        issue_status === 'unresolved' &&
        dayjs(gmt_create).add(30, 'day') < dayjs() &&
        state &&
        ['FAIL', 'WARNNING'].includes(state.toUpperCase())
      ) {
        return (
          <div className="retry-scan-list-empty">
            <ListEmpty
              content={''}
              desc={intl.get({
                id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.DetectionMoreThanDaysNot',
                defaultMessage: '检测已超30天，不支持查看问题详情',
              })}
              size="small"
              className="table-result"
              image="none"
              btns={[
                <Button
                  type="primary"
                  style={{ width: 88, marginTop: 8 }}
                  loading={isStarting}
                  size="small"
                  onClick={() => {
                    restartScan(false);
                  }}
                >
                  {intl.get({
                    id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.ReCheck',
                    defaultMessage: '重新检测',
                  })}
                </Button>,
              ]}
            />
          </div>
        );
      }
      return (
        <ListEmpty
          content={''}
          desc={
            issue_status === 'unresolved'
              ? intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.TheCurrentBranchHasNo',
                  defaultMessage: '当前分支暂无未解决的问题',
                })
              : intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.TheCurrentBranchHasNo.1',
                  defaultMessage: '当前分支暂无已解决的问题',
                })
          }
          size="small"
          imgType="500"
        />
      );
    }
  }

  expandedRowRender = () => {
    // record, index
    const { page, dataSource, isLoading } = this.state;
    const list = (dataSource && dataSource.list) || [];
    const amount = (dataSource && dataSource.amount) || 0;
    return (
      <React.Fragment>
        {isLoading || list.length > 0 ? (
          <div className="build-issue-list-subtable">
            <Table
              className={'issue-table'}
              dataSource={list}
              hasBorder={false}
              hasHeader={false}
              loading={isLoading}
              onRowClick={this.handleRowClick}
            >
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.Problem',
                  defaultMessage: '问题',
                })}
                dataIndex="title"
                className="pinpoint-issue-title-col"
                cell={this.renderTitle}
              />
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.FileName',
                  defaultMessage: '文件名',
                })}
                dataIndex="file_name"
                className="pinpoint-issue-file-col"
                cell={this.renderFile}
              />
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.ProblemLevel',
                  defaultMessage: '问题等级',
                })}
                dataIndex="level"
                className="pinpoint-issue-level-col"
                cell={this.renderLevel}
              />
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.State',
                  defaultMessage: '状态',
                })}
                dataIndex="status"
                className="pinpoint-issue-level-col"
                cell={this.renderStatus}
              />
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.ProblemIngress',
                  defaultMessage: '问题引入人',
                })}
                dataIndex="owner"
                className="pinpoint-issue-owner-col"
                cell={this.renderOwner}
              />
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.pinpointBuildIssuesList.issuesTable.ImportTime',
                  defaultMessage: '引入时间',
                })}
                dataIndex="intro_time"
                className="pinpoint-issue-time-col"
                cell={(value) => {
                  return utils.getBeautyTime(value);
                }}
              />
            </Table>
            <Pagination
              onChange={this.onPageNoChange}
              current={page}
              total={amount}
              pageSize={defaultPerPage}
              footerProps={{
                style: { margin: 0, paddingRight: 40 },
              }}
            />
          </div>
        ) : (
          this.renderEmptyList()
        )}
      </React.Fragment>
    );
  };

  render() {
    const { headerTitle, buildResult, updateCommitId } = this.props;
    const headerDataSource = [{ title: headerTitle, id: 0 }];
    const { openRowKeys, dataSource, isModalOpen, issue } = this.state;
    const { pathResource } = window.FORCE;
    return (
      <div>
        <Table
          dataSource={headerDataSource}
          hasBorder={false}
          expandedRowRender={this.expandedRowRender}
          expandedRowIndent={[0, 0]}
          hasHeader={false}
          openRowKeys={openRowKeys}
          onRowClick={this.toggleRow}
          onRowOpen={this.onRowOpen}
        >
          <Table.Column
            title="Title"
            dataIndex="title"
            cell={(item) => {
              return (
                <span className="sub-title" style={{ marginLeft: '-7px' }}>
                  {item}
                  {dataSource ? ` · ${dataSource.amount}` : null}
                </span>
              );
            }}
          />
        </Table>
        {isModalOpen && (
          <IssueIdialog
            issue={issue}
            onClose={this.onClose}
            build={buildResult}
            updateCommitId={updateCommitId}
            projectId={pathResource.id}
          />
        )}
      </div>
    );
  }
}
